package com.xt.base.dao.hibernate.userType;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

public class StringArray extends EmptyUserType implements Serializable{

	private static final long serialVersionUID = -6543661593759193926L;

	private static final String SPLITTER = "\u000f";   
	
	public Object deepCopy(Object value) throws HibernateException {
		if(value == null)return null;
		String[] sourse = (String[])value;
		String[] result = new String[sourse.length];
		System.arraycopy(sourse, 0, result, 0, sourse.length);
       return sourse;   
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		return (x == y)
		|| (x != null && y != null && java.util.Arrays.equals(
				(String[]) x, (String[]) y));
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
        String value = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);   
        if (value != null) {   
            return parse(value);   
        } else {   
            return null;   
        }   
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        if (value != null) {   
            String str = assemble((String[]) value);   
            Hibernate.STRING.nullSafeSet(st, str, index);   
        } else {   
            Hibernate.STRING.nullSafeSet(st, value, index);   
        }   
	}

	public Class<?> returnedClass() {
		return String[].class;
	}

	private String assemble(String[] sa){
		if(sa == null || sa.length == 0 )return null;
        StringBuffer strBuf = new StringBuffer();   
        for (int i = 0; i < sa.length - 1; i++) {   
            strBuf.append(sa[i]).append(SPLITTER);   
        }   
        strBuf.append(sa[sa.length-1]);   
        return strBuf.toString();   
	}

    private String[] parse(String value) {
    	if(StringUtils.isEmpty(value))return null;
    	String nativestr = "_temp_by_native_code";
       	if(value.startsWith(SPLITTER))value = nativestr + value;
       	if(value.endsWith(SPLITTER))value += nativestr;
        String[] strs = StringUtils.split(value, SPLITTER);
        String[] res = new String[strs.length];   
        for (int i = 0; i < strs.length; i++){
        	String addstr = strs[i];
        	addstr = nativestr.equals(addstr)?"":addstr;
        	res[i] = addstr;
        }
        return res;   
    }   
}
